<template>
  <Modal :value="showModal" title="修改密码" @on-ok="toChangePwd" @on-cancel="closeModal" :footer-hide="true">
    <Form ref="form" :model="formData" :rules="rules">
      <FormItem prop="originPassword" label="原密码">
        <Input v-model="formData.originPassword" type="password"></Input>
      </FormItem>
      <FormItem prop="newPassword" label="新密码">
        <Input v-model="formData.newPassword" type="password"></Input>
      </FormItem>
      <FormItem prop="againPassword" label="确认密码">
        <Input v-model="formData.againPassword" type="password"></Input>
      </FormItem>
      <Button type="primary" @click="toChangePwd">修改</Button>
    </Form>
  </Modal>
</template>

<script>
import {mapActions} from 'vuex';

export default {
  props: {
    showModal: {
      type: Boolean,
      default: false
    },
    userId: {
      type: String,
      default: ''
    }
  },
  data () {
    const pwdCheckValidate = (rule, value, callback) => {
      if (value == '') {
        callback(new Error('确认密码不能为空'));
      } else if (this.formData.newPassword != value) {
        callback(new Error('新密码和确认密码应相同'));
      } else {
        callback();
      }
    };
    return {
      formData: {
        originPassword: '',
        newPassword: '',
        againPassword: '',
      },
      rules: {
        originPassword: [
          {
            required: true,
            message: '原密码不能为空',
            trigger: 'blur'
          }
        ],
        newPassword: [
          {
            required: true,
            message: '新密码不能为空',
            trigger: 'blur'
          }
        ],
        againPassword: [
          {
            required: true,
            validator: pwdCheckValidate,
            trigger: 'blur',
          },
        ]
      }
    }
  },
  methods: {
    // 触发修改按钮
    toChangePwd () {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this._changePwd()
        }
      })
    },
    // 修改密码请求接口
    async _changePwd () {
      const url = '/editpassword'
      const res = await this.GET_DATA({
        dataUrl: url,
        userId: this.userId,
        originPassword: this.$handleEncrypt(this.formData.originPassword),
        // originPassword: this.formData.originPassword,
        password: this.$handleEncrypt(this.formData.newPassword)
      })
      if (res) {
        res.code === '0000' && this.$Message.success('操作成功')
        this.closeModal()
      }
    },
    // 关闭页面
    closeModal () {
      this.formData = {
        originPassword: '',
        newPassword: '',
        againPassword: '',
      }
      this.$emit('closeModal')
    },
    ...mapActions({
      GET_DATA: '_GET_DATA'
    })
  }
}
</script>